//
//  ViewController.m
//  bluetooth
//
//  Created by 周季阳 on 15/6/9.
//  Copyright (c) 2015年 switch. All rights reserved.
//

#import "ViewController.h"
#import "LZAudioTool.h"
#import "UIView+LZ.h"
#import "UIViewAdditions.h"
#import "BlueListTableViewCell.h"
#import <CoreMotion/CoreMotion.h>
#import "DeblockingViewController.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    CMMotionManager *_manager;
    NSTimer *AutoTimer;
}
@property (nonatomic, weak) UIImageView *bg;
@property (nonatomic, weak) UIImageView *up;
@property (nonatomic, weak) UIImageView *down;
@property (nonatomic, assign)BOOL zIsEnd;//判断是否摇一摇结束
@property(nonatomic,retain)UITableView *zTabelView;
@end

@implementation ViewController
@synthesize zIsEnd,zTabelView;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNav];
    navTitle.text = @"查找设备";
    self.navigationController.navigationBarHidden=YES;
    
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [self colorWithHexString:@"#F5F5F5"];
    
    //[[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
    
    //[self becomeFirstResponder];
    
    UIImageView *bg = [[UIImageView alloc] init];
    bg.image = [UIImage imageNamed:@"bg_shaking"];
    bg.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
    [self.view addSubview:bg];
    bg.userInteractionEnabled = YES;
    self.bg = bg;
    
    
    UIImageView *up = [[UIImageView alloc] init];
    up.image = [UIImage imageNamed:@"bg_yaoyao_above"];
    up.frame = CGRectMake(0, 0 , self.view.width, (self.view.height-64) * 0.5);
    [bg addSubview:up];
    self.up = up;
    
    
    UIImageView *down = [[UIImageView alloc] init];
    down.image = [UIImage imageNamed:@"bg_yaoyao_under"];
    down.frame = CGRectMake(0, up.bottom, self.view.width, (self.view.height-64) * 0.5);
    [bg addSubview:down];
    self.down = down;
    zIsEnd = YES;
    
    //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(clickBtn) name:@"clickBtn" object:nil];
    
    zActivity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.view.width/2-30, up.bottom+30, 60, 60)];
    
    [self.view addSubview:zActivity];
    
    zActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    
    zTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0,self.down.top+51+60, SCREEN_WIDTH, self.down.height-102-60)];
    zTabelView.backgroundColor = [self colorWithHexString:@"#F5F5F5"];
    zTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    zTabelView.delegate = self;
    zTabelView.dataSource = self;
    zTabelView.bounces = NO;
    [bg addSubview:zTabelView];
    zTabelView.hidden = YES;

    //1.0/60.0
    AutoTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(autoChange) userInfo:nil repeats:YES];
    
    
    _manager = [[CMMotionManager alloc]init];
    
    _manager.accelerometerUpdateInterval=1.0/60.0;
    
    [_manager startAccelerometerUpdates];
}
-(void)viewDidDisappear:(BOOL)animated{
    [AutoTimer invalidate];
    AutoTimer = nil;
}
-(void)autoChange

{
    NSLog(@"%.2f --%.2f --%.2f",_manager.accelerometerData.acceleration.x,_manager.accelerometerData.acceleration.y,_manager.accelerometerData.acceleration.z);
    //根据自己需求调节x y z
    
    if (fabs(_manager.accelerometerData.acceleration.x) > 1.1 || fabs(_manager.accelerometerData.acceleration.y) > 1.8 || fabs(_manager.accelerometerData.acceleration.z) > 1.2)
        
    {
        
        NSLog(@"我晃动了 。。。。。");
        if (zIsEnd == NO) {
            
        }else{
            zTabelView.hidden = YES;
            
            [zActivity startAnimating];
            
            [LZAudioTool playMusic:@"5018.mp3"];
            zIsEnd = NO;
            NSLog(@"motionBegan");
            
            CGFloat offset = self.bg.height/6;
            CGFloat duration = 0.2;
            
            //    [UIView animateWithDuration:duration animations:^{
            //            self.up.y -= offset;
            //            self.down.y += offset;
            //    }];
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:duration];
                [UIView setAnimationDelegate:self];
                self.up.y -= offset;
                self.down.y += offset;
                [UIView commitAnimations];
                NSLog(@"%2f",self.up.y);
            });
            zTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(pree) userInfo:nil repeats:NO];
            sleep(0.2);
        }

    }
    
}
#pragma mark - UitableView delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BlueListTableViewCell *cell = [[BlueListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    
    cell.zTitle.text = @"面膜机-51658461";
 
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [self colorWithHexString:@"#F5F5F5"];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DeblockingViewController *deblocking = [[DeblockingViewController alloc]init];
    [self.navigationController pushViewController:deblocking animated:YES];
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}


-(void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    [self becomeFirstResponder];
    
}


-(void)viewWillDisappear:(BOOL)animated {
    
    [self resignFirstResponder];
    
    [super viewWillDisappear:animated];
    
}

#pragma mark - 实现相应的响应者方法
/** 开始摇一摇 */
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
   
}
#pragma mark - 摇一摇结束
-(void)pree{
    if (zIsEnd== NO) {
        zTabelView.hidden = NO;
        [zTabelView reloadData];
        
         [zActivity stopAnimating];
        // 不是摇一摇运动事件
        
        NSLog(@"motionEnded");
        CGFloat offset = self.bg.height / 6;
        CGFloat duration = 0.2;
        [UIView animateWithDuration:duration animations:^{
            self.up.y += offset;
            self.down.y -= offset;
        }completion:^(BOOL finished){
            [LZAudioTool playMusic:@"5012.wav"];
            zIsEnd = YES;
        }];
    }
}
/** 摇一摇结束（需要在这里处理结束后的代码） */
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
//    if (zIsEnd== NO) {
//        
//    // 不是摇一摇运动事件
//    if (motion != UIEventSubtypeMotionShake) return;
//        [zActivity stopAnimating];
//
//    NSLog(@"motionEnded");
//    CGFloat offset = self.bg.height / 4;
//    CGFloat duration = 0.2;
//    [UIView animateWithDuration:duration animations:^{
//        self.up.y += offset;
//        self.down.y -= offset;
//    }];
//    zIsEnd = YES;
//    }
}

/** 摇一摇取消（被中断，比如突然来电） */
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
//    if (zIsEnd == NO) {
//        [zActivity stopAnimating];
//
//    NSLog(@"motionCancelled");
//    CGFloat offset = self.bg.height / 4;
//    CGFloat duration = 0.2;
//    [UIView animateWithDuration:duration animations:^{
//        self.up.y += offset;
//        self.down.y -= offset;
//    }];
//    zIsEnd = YES;
//    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
